package com.ruoyi.iot.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.ruoyi.iot.domain.mongo.DeviceSensorMO;
import com.ruoyi.iot.service.IMongoService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class IotFilterMongoServiceImpl implements IMongoService {

    @Autowired
    private MongoTemplate mongoTemplate;

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");



    @Override
    public Boolean insertMongo(Long filterId, String devId, JSONObject environment_data) {

        //从产品角度来看，产品筛选设备
        String actual_key_collection = String.format("display_actual.%s.%s",filterId,devId);
        //从设备角度来看，设备筛选，到历史记录
        String history_key_collection = String.format("display_history.%s.%s",devId,filterId);

       DeviceSensorMO deviceSensorMO = new DeviceSensorMO();
       deviceSensorMO.setTime(System.currentTimeMillis());
       deviceSensorMO.setData(environment_data);

       mongoTemplate.dropCollection(actual_key_collection);
       mongoTemplate.save(deviceSensorMO,actual_key_collection);

       if(!mongoTemplate.collectionExists(history_key_collection)) {
           mongoTemplate.createCollection(history_key_collection);
       }

       mongoTemplate.save(deviceSensorMO,history_key_collection);
       return true;
    }

    @Override
    public DeviceSensorMO queryActualInfo(String devId, Long filterId) {
        String actual_key_collection = String.format("display_actual.%s.%s",filterId,devId);
        MongoCollection<Document> collection = mongoTemplate.getCollection(actual_key_collection);
        //全查
        FindIterable<Document> find = collection.find();
        //迭代器对象
        MongoCursor<Document> iterator = find.iterator();
        if(iterator.hasNext()) {
            String jsonValue = iterator.next().toJson();

            DeviceSensorMO sensorMO = JSON.parseObject(jsonValue, DeviceSensorMO.class);

            return sensorMO;
        }
        return null;
    }

    @Override
    public List<DeviceSensorMO> queryHistoryInfo(String devId, Long filterId, Long page, Long pageNum) {

        String history_key_collection = String.format("display_history.%s.%s",devId,filterId);
        MongoCollection<Document> collection = mongoTemplate.getCollection(history_key_collection);
        //全查
        Long index = (page - 1) * pageNum;
        FindIterable<Document> find = collection.find().skip(index.intValue()).limit(pageNum.intValue());
        MongoCursor<Document> iterator = find.iterator();
        List<DeviceSensorMO> arrayList = new ArrayList<>();
        while (iterator.hasNext()) {
            String jsonValue = iterator.next().toJson();
            DeviceSensorMO sensorMO = JSON.parseObject(jsonValue,DeviceSensorMO.class);
            arrayList.add(sensorMO);
        }

        return arrayList;
    }

    @Override
    public Long queryHistoryTotal(String devId, Long filterId) {
        String history_key_collection = String.format("display_history.%s.%s",devId,filterId);
        MongoCollection<Document> collection = mongoTemplate.getCollection(history_key_collection);
        Long num = collection.countDocuments();
        return num;
    }


    @SneakyThrows
    @Override
    public List<DeviceSensorMO> queryCurrentSensorVO(String devId, Long filterId, Integer interval, Integer numbs) {
        String history_key_collection = String.format("display_history.%s.%s",devId,filterId);
        MongoCollection<Document> collection = mongoTemplate.getCollection(history_key_collection);
        Long index = collection.countDocuments() - 1;
        FindIterable<Document> find = collection.find().skip(index.intValue()).limit(1);
        String jsonValue = find.iterator().next().toJson();
        DeviceSensorMO sensorMO = JSON.parseObject(jsonValue,DeviceSensorMO.class);
       // log.info("current:" + df.format(sensorMO.getTime()));
        if(sensorMO != null) {
            Long lastTime =  sensorMO.getTime()- interval * 24 * 60 * 60 * 1000;
            String lastStr = df.format(lastTime);
            //log.info("last:" + lastStr);
            // 大于某个时间
            BasicDBObject ageObj = new BasicDBObject("time",new BasicDBObject("$gte", lastTime));
            MongoCursor<Document> iterator = collection.find(ageObj).iterator();
            List<DeviceSensorMO> findList = new ArrayList<>();
            List<DeviceSensorMO> rstList = new ArrayList<>();
            while (iterator.hasNext()) {
                String dataValue = iterator.next().toJson();
                log.info("current:" + dataValue);
                DeviceSensorMO dataSensorMO = JSON.parseObject(dataValue,DeviceSensorMO.class);
                findList.add(dataSensorMO);
            }

            Integer skip = findList.size() / numbs;
            for(int i = 0; i < numbs; i++) {
               Integer in = (i + 1) * skip;
               DeviceSensorMO item = findList.get(in);
               rstList.add(item) ;
            }


            return rstList;
        }

        return null;
    }


   // @PostConstruct
    public void test() {
        String devId = "000001";
        Long filterId = 6L;
        //从产品角度来看，产品筛选设备
//        String actual_key_collection = String.format("display_actual.%s.%s",filterId,devId);
//        //从设备角度来看，设备筛选，到历史记录
//        String history_key_collection = String.format("display_history.%s.%s",devId,filterId);
//        mongoTemplate.dropCollection(actual_key_collection);
//        mongoTemplate.dropCollection(history_key_collection);
//        DeviceSensorMO deviceSensorMO =  queryActualInfo(devId,filterId);
//        log.info("actual:" + JSONObject.toJSONString(deviceSensorMO));
//
//        List<DeviceSensorMO> deviceSensorMOS =  queryHistoryInfo(devId,filterId,2l,10l);
//        log.info("history:" + JSONObject.toJSONString(deviceSensorMOS));
//
//        log.info("num:" + queryHistoryTotal(devId,filterId));
      //  queryCurrentSensorVO(devId,filterId,1,10);
    }





}
